package org.jeecg.modules.youlgl.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecg.modules.youlgl.entity.HqYlgl;
import org.jeecg.modules.youlgl.service.IHqYlglService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 油料管理
 * @Author: jeecg-boot
 * @Date: 2020-06-16
 * @Version: V1.0
 */
@Api(tags = "油料管理")
@RestController
@RequestMapping("/youlgl/hqYlgl")
@Slf4j
public class HqYlglController extends JeecgController<HqYlgl, IHqYlglService> {
    @Autowired
    private IHqYlglService hqYlglService;

    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(HqYlgl hqYlgl,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {

        Page<HqYlgl> page = new Page<HqYlgl>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqYlgl> iPage = hqYlglService.myApplyList(page, user, hqYlgl);

        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }

        return Result.ok(iPage);
    }

    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(HqYlgl hqYlgl,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqYlgl> page = new Page<HqYlgl>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqYlgl> iPage = hqYlglService.myTodoTasks(page, user, hqYlgl);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(HqYlgl hqYlgl,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqYlgl> page = new Page<HqYlgl>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<HqYlgl> iPage = hqYlglService.myDoneTasks(page, user, hqYlgl);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }
        return Result.ok(page);
    }


    // 车号查历史充值记录
    @GetMapping(value = "/queryByChepNu")
    public Result<?> queryByChepNu(@RequestParam(value = "chepNu",required = false) String chepNu) {

        if (chepNu==null||chepNu==""){
            return Result.error("请填写车牌！");
        }
//        HqYlgl hqYlgl = hqYlglService.getOne(new QueryWrapper<HqYlgl>().eq("chepnu", chepNu).orderByDesc("create_time"), false);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<HqYlgl> hqYlgl2=hqYlglService.myApplyList2(loginUser,chepNu);
        hqYlgl2.forEach(record -> {
            if (null != record.getEndTime()) {
                record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
            } else {
                if (null != record.getAuditStatus()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                } else {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                }
            }
            });


        if (hqYlgl2.size()==0)
            return Result.error("没有找到这辆车的上次加油里程");

        HqYlgl hqYlgl=hqYlgl2.get(0);
        if(!hqYlgl.getProcessStatus().equals(2))
            return Result.error("上次提交的审批还未完成，等待完成后再发起新流程！");

//        List<HqYlgl> list = hqYlglService.list(new QueryWrapper<HqYlgl>().eq("chepnu", chepNu).orderByDesc("create_time"));

//        HqYlgl hqYlgl = null;
//        if (CollectionUtils.isNotEmpty(list))
//            hqYlgl = list.get(0);

        if (hqYlgl != null)
            return Result.ok(hqYlgl);
        else
            return Result.error("没有找到这辆车的上次加油里程！");
    }

    /**
     * 分页列表查询
     *
     * @param hqYlgl
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "油料管理-分页列表查询")
    @ApiOperation(value = "油料管理-分页列表查询", notes = "油料管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HqYlgl hqYlgl,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HqYlgl> queryWrapper = QueryGenerator.initQueryWrapper(hqYlgl, req.getParameterMap());
        queryWrapper.eq("shenqr_id", ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());
        Page<HqYlgl> page = new Page<HqYlgl>(pageNo, pageSize);
        IPage<HqYlgl> pageList = hqYlglService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param hqYlgl
     * @return
     */
    @AutoLog(value = "油料管理-添加")
    @ApiOperation(value = "油料管理-添加", notes = "油料管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HqYlgl hqYlgl) {
        int count = hqYlglService.count();
        hqYlgl.setId("CLYYSQ" + DateUtil.format(new Date(), "yyyyMMdd") + String.format("%04d", count));
        hqYlgl.setStatus(1);
        hqYlgl.setShangcjypldsgls(hqYlgl.getBencjypldsgls());
        hqYlgl.setLastapplygas(hqYlgl.getGas());
        hqYlgl.setLastapplydate(new Date());

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqYlglService.startFlow(hqYlgl, loginUser);

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hqYlgl
     * @return
     */
    @AutoLog(value = "油料管理-编辑")
    @ApiOperation(value = "油料管理-编辑", notes = "油料管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HqYlgl hqYlgl) {
        hqYlgl.setStatus(1);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqYlglService.applyAgain(hqYlgl, loginUser);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "油料管理-通过id删除")
    @ApiOperation(value = "油料管理-通过id删除", notes = "油料管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hqYlglService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "油料管理-批量删除")
    @ApiOperation(value = "油料管理-批量删除", notes = "油料管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hqYlglService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "油料管理-通过id查询")
    @ApiOperation(value = "油料管理-通过id查询", notes = "油料管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HqYlgl hqYlgl = hqYlglService.getById(id);
        if (hqYlgl == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(hqYlgl);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hqYlgl
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqYlgl hqYlgl) {
        return super.exportXls(request, hqYlgl, HqYlgl.class, "油料管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HqYlgl.class);
    }

    @AutoLog(value = "任务列表")
    @ApiOperation(value = "任务列表", notes = "任务列表")
    @GetMapping(value = "/tasklist")
    public Result<?> taskList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqYlgl> page = hqYlglService.taskList(loginUser.getUsername(), pageNo, pageSize);

        return Result.ok(page);
    }

    @AutoLog(value = "任务审批")
    @ApiOperation(value = "任务审批", notes = "任务审批")
    @PostMapping(value = "/completetask")
    public Result<?> completeTask(@RequestBody Map params) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqYlglService.complateTask(loginUser, (String) params.get("taskId"), (Integer) params.get("auditStatus"), (String) params.get("memo"));

        return Result.ok("操作成功");
    }
}
